package com.smsc.headend.task.engine.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import cn.hutool.json.JSONUtil;
import com.emeter.energyip.amiinterface.MeterReadsReplyMessageDocument;
import com.smsc.headend.common.enums.VirtualProfileSrc;
import com.smsc.headend.module.data.dto.TaskDataDTO;
import com.smsc.headend.module.data.entity.RdDcuReadsVp;
import com.smsc.headend.module.data.entity.RdMeterReadsLp;
import com.smsc.headend.module.data.entity.RdMeterReadsVp;
import com.smsc.headend.module.task.consts.TaskKafkaTopic;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.dto.TaskResult;
import com.smsc.headend.module.task.enums.TaskType;
import com.smsc.headend.task.engine.service.RdDcuReadsVpService;
import com.smsc.headend.task.engine.service.RdMeterReadsVpService;
import com.smsc.headend.task.engine.service.RdVirtualProfileService;
import com.smsc.headend.task.engine.utils.DdsXmlGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * (业务实现)
 *
 * @author wjh
 * @date 2022/1/10 9:30.
 */
@Service
@Slf4j
public class RdVirtualProfileServiceImpl implements RdVirtualProfileService {

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    RdMeterReadsVpService rdMeterReadsVpService;

    @Autowired
    RdDcuReadsVpService rdDcuReadsVpService;

    @Autowired
    DdsXmlGenerateUtil ddsXmlGenerateUtil;

    @Override
    public void saveRdRecord(Task task, AtomicTask atomicTask, Object value) {
        try {
            Long tv = SystemClock.now() / 1000;
            Long meterId = task.getMeterId();
            RdMeterReadsVp rdMeterReadsVp = null;
            Map<String, Object> m = JSONUtil.toBean(atomicTask.getAtomicTaskParam(), Map.class);
            Map<String, Object> taskParamMap = JSONUtil.toBean(task.getParamJson(), Map.class);
            Long vpTemplateId = Long.valueOf(String.valueOf(taskParamMap.get("vpTemplateId")));
            Long dataItemId = Long.valueOf(String.valueOf(m.get("dataItemId")));
            int src = getSrc(task.getTaskType());
            if (null != meterId) {
                rdMeterReadsVp = new RdMeterReadsVp();
                rdMeterReadsVp.setMeterId(meterId);
                rdMeterReadsVp.setTaskNo(task.getTaskNo());
                rdMeterReadsVp.setValue(String.valueOf(value));
                rdMeterReadsVp.setSubDataItemId(dataItemId);
                rdMeterReadsVp.setTvUpdate(tv);
                rdMeterReadsVp.setTv(tv);
                rdMeterReadsVp.setVpTemplateId(vpTemplateId);
                rdMeterReadsVp.setSrc(src);
                List<RdMeterReadsVp> list = new ArrayList<>();
                list.add(rdMeterReadsVp);
                rdMeterReadsVpService.batchSaveRd(list);
            } else {
                if (taskParamMap.containsKey("dcuId")) {
                    Long dcuId = Long.valueOf(String.valueOf(taskParamMap.get("dcuId")));
                    RdDcuReadsVp rdDcuReadsVp = new RdDcuReadsVp();
                    rdDcuReadsVp.setDcuId(dcuId);
                    rdDcuReadsVp.setTaskNo(task.getTaskNo());
                    rdDcuReadsVp.setValue(String.valueOf(value));
                    rdDcuReadsVp.setSubDataItemId(dataItemId);
                    rdDcuReadsVp.setTvUpdate(tv);
                    rdDcuReadsVp.setTv(tv);
                    rdDcuReadsVp.setVpTemplateId(vpTemplateId);
                    rdDcuReadsVp.setSrc(src);
                    List<RdDcuReadsVp> list = new ArrayList<>();
                    list.add(rdDcuReadsVp);
                    rdDcuReadsVpService.batchSaveRd(list);
                }
            }
        } catch (Exception e) {
            log.error("save vp data error,taskNo:{}", task.getTaskNo());
        }
    }

    @Override
    public void rdDataTransfer(TaskResult taskResult) {
        kafkaTemplate.send(TaskKafkaTopic.VIRTUAL_PROFILE_READ_TRANSFER, JSONUtil.toJsonStr(taskResult).getBytes(Charset.forName("utf-8")));
    }

    @Override
    public void sendRdDataToAdapter(TaskResult taskResult) {
        Map<String, Object> taskParamMap = JSONUtil.toBean(taskResult.getParamJson(), Map.class);
        Long tvUpdate = Long.valueOf(String.valueOf(taskParamMap.get("tv")));
        String taskType = (String) taskParamMap.get("taskType");
        String vpTemplateIdStr = String.valueOf(taskParamMap.get("vpTemplateId"));
        Long vpTemplateId = Long.valueOf(vpTemplateIdStr);
        Long meterId = null;
        if (taskParamMap.containsKey("meterId")) {
            meterId = ((Integer) taskParamMap.get("meterId")).longValue();
        }
        List<TaskDataDTO> taskDataDTOS = JSONUtil.toList(JSONUtil.parseArray(JSONUtil.toJsonStr(taskResult.getResultData())), TaskDataDTO.class);
        //解析成RD_METER_READS_VP并入库
        int src = getSrc(taskType);
        List<RdMeterReadsVp> rdMeterReadsVps = new ArrayList<>();
        for (TaskDataDTO taskDataDTO : taskDataDTOS) {
            RdMeterReadsVp rdMeterReadsVp = null;
            String key = taskDataDTO.getKey();
            Long dataItemId = Long.valueOf(key);
            if (null != meterId) {
                rdMeterReadsVp = new RdMeterReadsVp();
                rdMeterReadsVp.setMeterId(meterId);
                rdMeterReadsVp.setTaskNo(taskResult.getTaskNo());
                rdMeterReadsVp.setValue(String.valueOf(taskDataDTO.getValue()));
                rdMeterReadsVp.setSubDataItemId(dataItemId);
                rdMeterReadsVp.setTvUpdate(tvUpdate);
                rdMeterReadsVp.setTv(tvUpdate);
                rdMeterReadsVp.setVpTemplateId(vpTemplateId);
                rdMeterReadsVp.setSrc(src);
                rdMeterReadsVps.add(rdMeterReadsVp);
            }
//            } else {
//                if (taskParamMap.containsKey("dcuId")) {
//                    Long dcuId = Long.valueOf(String.valueOf(taskParamMap.get("dcuId")));
//                    RdDcuReadsVp rdDcuReadsVp = new RdDcuReadsVp();
//                    rdDcuReadsVp.setDcuId(dcuId);
//                    rdDcuReadsVp.setTaskNo(taskResult.getTaskNo());
//                    rdDcuReadsVp.setValue(String.valueOf(taskDataDTO.getValue()));
//                    rdDcuReadsVp.setSubDataItemId(dataItemId);
//                    rdDcuReadsVp.setTvUpdate(tvUpdate);
//                    rdDcuReadsVp.setTv(tvUpdate);
//                    rdDcuReadsVp.setVpTemplateId(vpTemplateId);
//                    rdDcuReadsVp.setSrc(src);
//                    rdDcuReadsVps.add(rdDcuReadsVp);
//                }
//            }
        }
//        rdDcuReadsVpService.batchSaveRd(rdDcuReadsVps);
//        rdMeterReadsVpService.batchSaveRd(rdMeterReadsVps);
        TaskResult taskResult1 = new TaskResult();
        taskResult1.setTaskNo(taskResult.getTaskNo());
        taskResult1.setMessageId(taskResult.getMessageId());
        List<RdMeterReadsLp> rdMeterReadsLps = new ArrayList<>();
        for (RdMeterReadsVp rdMeterReadsVp : rdMeterReadsVps) {
            //复用eipdocument转换方法，将虚拟曲线数据转化为LP数据，由于虚拟曲线没有lpDataItemId字段，转换时需要根据lpDataItemId字段来分组，所以去一个特殊值作为虚拟曲线的lpDataItemId字段
            RdMeterReadsLp rdMeterReadsLp = new RdMeterReadsLp();
            rdMeterReadsLp.setMeterId(rdMeterReadsVp.getMeterId());
            //如果value是日期则需要转化为秒
            String datePattern1 = "([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2]|[1-9])(-(0[1-9]|[1-2][0-9]|3[0-1]|[1-9]))?)? ([01]?[0-9]|2[0-3])(:[0-5]?[0-9](:[0-5]?[0-9]|60)?)?";
            Pattern pattern = Pattern.compile(datePattern1);
            Matcher match = pattern.matcher(rdMeterReadsVp.getValue());
            if (match.matches()) {
                rdMeterReadsLp.setValue(Convert.toStr(DateUtil.parse(rdMeterReadsVp.getValue(), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
            } else {
                rdMeterReadsLp.setValue(rdMeterReadsVp.getValue());
            }
            rdMeterReadsLp.setLpDataItemId(9999999L);
            rdMeterReadsLp.setTv(rdMeterReadsVp.getTv());
            rdMeterReadsLp.setSrc(rdMeterReadsVp.getSrc());
            rdMeterReadsLp.setTvUpdate(rdMeterReadsVp.getTvUpdate());
            rdMeterReadsLp.setDataItemId(rdMeterReadsVp.getSubDataItemId());
            rdMeterReadsLps.add(rdMeterReadsLp);
        }
        taskResult1.setParamJson(taskResult.getParamJson());
        MeterReadsReplyMessageDocument document = ddsXmlGenerateUtil.getDocumentLp(rdMeterReadsLps);
        taskResult1.setDocumentData(document.toString());
        kafkaTemplate.send(TaskKafkaTopic.TASK_COMPLETE_RESULT_FROM_UTE_TO_ADAPTER, JSONUtil.toJsonStr(taskResult1).getBytes(Charset.forName("utf-8")));
    }


    private int getSrc(String taskType) {
        int src = VirtualProfileSrc.HES.getId();
        if (TaskType.ScheduleRead_Virtual_Profile.name().equals(taskType)) {
            src = VirtualProfileSrc.AUTO.getId();
        } else if (TaskType.UAA_MeterReads.name().equals(taskType)) {
            src = VirtualProfileSrc.MDM.getId();
        } else if (TaskType.ODR_Virtual_Profile.name().equals(taskType)) {
            src = VirtualProfileSrc.HES.getId();
        }
        return src;
    }
}
